package initialize

import (
	"database/sql"
	"fmt"
	"go_19/config"
	"go_19/global"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
)

// 初始化数据库并产生数据库全局变量
func Mysql() {
	c := global.GVA_CONFIG.Mysql
	if db, sqlDB, err := ConMysql(c); err != nil {
		log.Fatal("MySQL启动异常!!", c)
		defer func() {
			s, _ := db.DB()
			s.Close()
		}()
		panic(err)
	} else {
		global.GVA_DB = db
		global.GVA_SQLDB = sqlDB
	}
}

func ConMysql(c config.Mysql) (*gorm.DB, *sql.DB, error) {
	if db, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@(%s)/%s?%s",
		c.Username,
		c.Password,
		c.Path,
		c.Dbname,
		c.Config)), &gorm.Config{
		Logger: logger.New(
			log.New(log.Writer(), "\r\n", log.LstdFlags), // io writer
			logger.Config{
				// SlowThreshold: time.Second,   // 慢 SQL 阈值
				LogLevel:                  logger.Info, // 日志级别
				IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
				Colorful:                  true,        // 启用彩色打印
			},
		),
	}); err != nil {
		return nil, nil, err
	} else {
		sqlDb, err := db.DB()
		sqlDb.SetMaxIdleConns(c.MaxIdleConns)
		sqlDb.SetMaxOpenConns(c.MaxOpenConns)

		return db, sqlDb, err
	}
}
